/**
 * checksum自动生成和校验。所谓checksum，是指相加前面所有的字节数据，返回1个字节的校验码。
 * Created by jinlei on 14-8-16.
 */

(function(){

  var checksum = {};
  var root = this;

  var _result = {};


  /**
   * 生成校验码
   * @param buffer
   * @param start 默认0
   * @param end 默认buffer长度减1
   * @returns {*} 字符串形式的16进制的校验码
   */
  checksum.checksum = function(buffer, start, end) {
    var sum = 0;
    start = start || 0;
    end = end || buffer.length - 1
    for (var i = start; i < end; i++) {
      sum += buffer[i];
    }

    var chksum = sum & 0xff;

    var chksumStr;
    if (chksum < 16) {
      chksumStr = "0" + chksum.toString(16);
    } else {
      chksumStr = chksum.toString(16);
    }

    return chksumStr;
  };

  /**
   * 校验checksum。
   * @param buffer Buffer类型的数据
   * @param chksum 字符串形式的16进制的校验码
   * @returns {boolean}
   */
  checksum.validate = function(buffer, chksum) {
    var bChksum = buffer.slice(buffer.length-1).toString('hex');
    if (chksum === bChksum) {
      return true;
    }
    return false;
  }

  //导出成NodeJS模块
  module.exports = checksum;
})();